﻿using System;
using System.Collections.Generic;
using System.Text;
using DBUtil.Expressions;

namespace DBUtil.Provider.SqlServer.Expressions
{
    /// <summary>
    /// SqlServer中的日期时间运算符
    /// </summary>
    public class SqlServerDateTimeExpression : DateTimeExpression
    {
        /// <summary>
        /// 默认实例
        /// </summary>
        public static SqlServerDateTimeExpression Default = new SqlServerDateTimeExpression();

        /// <summary>
        /// 默认的日期时间类型
        /// </summary>
        public override string DefaultDateTimeType => "datetime2";

        /// <summary>
        /// 获取当前时间
        /// </summary>
        public override string Current => "GetDate()";

        /// <summary>
        /// 当前时间加上指定的天数
        /// </summary>
        /// <param name="day">加上的天数</param>
        public override string GetCurrentAddDay(long day) => $"DATEADD(day,{day},GetDate()) ";

        /// <summary>
        /// 当前时间加上指定的小时数
        /// </summary>
        /// <param name="hour">加上的小时数</param>
        public override string GetCurrentAddHour(long hour) => $"DATEADD(hour,{hour},GetDate()) ";

        /// <summary>
        /// 当前时间加上指定的分钟数
        /// </summary>
        /// <param name="minute">加上的分钟数</param>
        /// <returns></returns>
        public override string GetCurrentAddMinute(long minute) => $"DATEADD(minute,{minute},GetDate()) ";

        /// <summary>
        /// 当前时间加上指定的秒数
        /// </summary>
        /// <param name="second">加上的秒数</param>
        /// <returns></returns>
        public override string GetCurrentAddSecond(long second) => $"DATEADD(second,{second},GetDate()) ";

        /// <summary>
        /// 获取时间的字符串表示
        /// </summary>
        /// <param name="datetime">指定的时间</param>
        /// <returns></returns>
        public override string GetStringInSql(DateTime datetime) => $"'{datetime.ToString("yyyy-MM-dd HH:mm:ss.fff")}'";

        /// <summary>
        /// 获取日期时间的过滤条件
        /// </summary>
        /// <param name="colName">列名</param>
        /// <param name="start">开始时间</param>
        /// <param name="end">结束时间</param>
        /// <param name="includeStart">是否包含开始时间</param>
        /// <param name="includeEnd">是否包含结束时间</param>
        /// <returns></returns>
        public override string GetFilterString(string colName, DateTime? start, DateTime? end, bool includeStart = true, bool includeEnd = false)
        {
            if (start == null && end == null) return "";
            var filterSql = "";
            if (start != null)
            {
                filterSql += $" and {colName} {(includeStart ? ">=" : ">")}'{start.Value.ToString("yyyy-MM-dd HH:mm:ss.fff")}'";
            }
            if (end != null)
            {
                filterSql += $" and {colName} {(includeEnd ? "<=" : "<")}'{end.Value.ToString("yyyy-MM-dd HH:mm:ss.fff")}'";
            }
            return filterSql;
        }
    }
}
